
package com.csc440.team2.activity;

import java.util.ArrayList;
import java.util.List;


import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnCreateContextMenuListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;


import com.csc440.team2.SmilConstants;
import com.csc440.team2.database.entities.FolderType;
import com.csc440.team2.database.entities.Message;
import com.csc440.team2.smil.SMILMessage;
import com.csc440.team2.smil.SMILReadException;
import com.csc440.team2.smil.SMILReader;


/**
 * ListView tab that shows messages saved as drafts in the database.
 * 
 * @author Santiago Jamriska, Brad Gardner
 * 
 */
public class DraftsTab extends ListActivity
{
    protected ListView lv;
    private List<SMILMessage> smilMessages;
    protected static final int CONTEXTMENU_DELETEITEM = Menu.FIRST;
    protected static final int CONTEXTMENU_DELETEALL = (Menu.FIRST + 1);


    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        // retrieve the list of messages to display
        smilMessages = getSMILMessages();

        setListAdapter(new ArrayAdapter<SMILMessage>(this, R.layout.drafts, smilMessages));

        lv = getListView();
        lv.setTextFilterEnabled(true);

        // click action selects a message
        lv.setOnItemClickListener(new OnItemClickListener()
        {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id)
            {
                Intent myIntent = new Intent(view.getContext(), Components.class);
                myIntent.putExtra(SmilConstants.MESSAGE, smilMessages.get(position));
                startActivity(myIntent);
            }
        });

        // delete and delete all options on the press and hold action
        lv.setOnCreateContextMenuListener(new OnCreateContextMenuListener()
        {
            public void onCreateContextMenu(ContextMenu conMenu, View arg1, ContextMenu.ContextMenuInfo menuInfo)
            {
                conMenu.setHeaderTitle("Menu");
                conMenu.add(Menu.NONE, CONTEXTMENU_DELETEITEM, 1, "Delete");
                conMenu.add(Menu.NONE, CONTEXTMENU_DELETEALL, 2, "Delete All");
            }
        });
    }


    /*
     * Retrieves SMIL Messages from the database and creates SMILMessage objects
     * from them
     */
    private List<SMILMessage> getSMILMessages()
    {
        List<SMILMessage> messages = new ArrayList<SMILMessage>();
        try
        {
            // retrieve all messages in the data store
            List<Message> messageList = Message.getAll(this);

            // for each message in the data store, create a SMILMessage object
            int counter = 1;
            for (Message currentMessage : messageList)
            {
                if (currentMessage.getFolder() == FolderType.DRAFT)
                {
                    SMILMessage smilMessage = SMILReader.parseMessage(currentMessage.getMessage());

                    // TODO implement a subject in the message instead of using
                    // a counter
                    smilMessage.setSubject("Message " + counter);
                    smilMessage.setDatabaseId(currentMessage.getId());
                    messages.add(smilMessage);
                }

                ++counter;
            }
        }
        catch (SMILReadException e)
        {
            Log.e("Get Messages", "Could not retrieve SMIL messages", e);
        }
        return messages;
    }


    private void deleteMessage(SMILMessage messageD)
    {
        try
        {
            Message dbMessage;
            dbMessage = new Message(messageD.getDatabaseId(), messageD.getXml(), FolderType.DRAFT, true, "");

            /*
             * TODO implement a rollback to make delete functionality autonomous
             * for deleting from database and list view
             */

            // attempt to delete the message from the database
            boolean deleted = dbMessage.delete(this);

            // log the result and update the list view if necessary
            if (deleted)
            {
                Log.i("Delete", "Message Deleted");
                // try to find the message in the list to delete
                int index = 0;
                int removeIndex = -1;
                for (SMILMessage message : smilMessages)
                {
                    if (message.getDatabaseId() == messageD.getDatabaseId())
                        removeIndex = index;
                    ++index;
                }

                // remove the message if it was found in the list
                if (removeIndex != -1)
                    smilMessages.remove(removeIndex);

                // update the list view
                lv.setAdapter(new ArrayAdapter<SMILMessage>(this, R.layout.drafts, smilMessages));
            }
            else
            {
                Log.i("Delete", "Failed to delete message");
            }
        }
        catch (SMILReadException e)
        {
            Log.e("Delete", "Could not delete message", e);
        }
    }


    @Override
    public boolean onContextItemSelected(MenuItem aItem)
    {
        AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo) aItem.getMenuInfo();

        /* Switch on the ID of the item, to get what the user selected. */
        switch (aItem.getItemId())
        {
            case CONTEXTMENU_DELETEITEM:
                deleteMessage(smilMessages.get(menuInfo.position));
                return true; /* true means: "we handled the event". */

            case CONTEXTMENU_DELETEALL:
                for (SMILMessage message : smilMessages)
                    deleteMessage(message);
                return true; /* true means: "we handled the event". */

        }
        return false;
    }
}
